package com.example.park.service.impl;

import com.example.park.dao.ParkShareDao;
import com.example.park.dao.ParkingDao;
import com.example.park.dao.UserDao;
import com.example.park.entity.UserEntity;
import com.example.park.entityVO.ParkingVO;
import com.example.park.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private ParkShareDao parkShareDao;

    @Autowired
    private ParkingDao parkingDao;

    @Override
    public UserEntity adminLogin(String username, String password) {
        return userDao.adminLogin(username, password);
    }

    @Override
    public UserEntity weiXinLogin(Integer state, String openid) {
        UserEntity user = new UserEntity();
        user.setState(state);
        user.setOpenId(openid);
        List<UserEntity> users = userDao.queryByParam(user);
        if (users.size() > 0) {
            return users.get(0);
        }
        if (userDao.insert(user) > 0) {
            return user;
        }
        return null;
    }

    @Override
    public List<UserEntity> queryByDim(String param) {
        return userDao.queryByDim(param);
    }

    @Override
    public List<UserEntity> queryByParam(UserEntity user) {
        return userDao.queryByParam(user);
    }

    @Override
    public boolean insert(UserEntity user) {
        return userDao.insert(user) > 0;
    }

    @Override
    public boolean update(UserEntity user) {
        return userDao.update(user) > 0;
    }

    @Override
    public boolean delete(Integer id) {
        return userDao.delete(id) > 0;
    }

    @Override
    @Transactional
    public boolean adminDelete(Integer id) {
        ParkingVO parkingVO = new ParkingVO();
        parkingVO.setuId(id);
        List<ParkingVO> parkingVOS = parkingDao.queryVOByParam(parkingVO);
        if (parkingVOS.size() > 0) {
            List<Integer> parkingId = parkingVOS.stream().map(item -> {return id;}).collect(Collectors.toList());
            for (Integer i : parkingId) {
                parkingDao.delete(i);
            }
            parkShareDao.deleteByPId(parkingId);
        }
        return userDao.delete(id) > 0;
    }
}
